<template>
  <div class="dashboard-container">
    <div class="app-container">
      <Toputil :before="total">
        <template slot="before"></template>
        <template slot="after">
          <el-button type="primary" size="mini" @click="upload">导入xlsx</el-button>
          <el-button type="success" size="mini" @click="dataExport">导出xlsx</el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="dialogFormVisible=true"
            :disabled="!checkPoints('POINT-USER-ADD')"
          >新增员工</el-button>
        </template>
      </Toputil>
      <el-card style="margin:10px 0">
        <el-table :data="data" style="width: 100%">
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="username" label="姓名" sortable width="140"></el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable width="140"></el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable width="140"></el-table-column>
          <el-table-column
            prop="inServiceStatus"
            label="聘用形式"
            sortable
            width="180"
            :formatter="formatterInServiceStatus"
          ></el-table-column>
          <el-table-column prop="departmentName" label="部门" sortable width="140"></el-table-column>
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            sortable
            width="280"
            :formatter="formatDate"
          ></el-table-column>
          <el-table-column label="状态" sortable width="140">
            <template slot-scope="{row}">
              <el-switch :value="row.enableState==1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="295">
            <template slot-scope="{row}">
              <a @click="showEmployee(row.id)">查看</a>
              <a>转正</a>
              <a>调岗</a>
              <a>离职</a>
              <a @click="role(row)">角色</a>
              <a class="del" @click="delEmployee(row.id)">删除</a>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :page-size="size"
          @current-change="handleCurrentChange"
          :current-page="page"
          layout="prev, pager, next"
          :total="total"
          align="center"
        ></el-pagination>
      </el-card>

      <el-dialog title="新增员工" :visible.sync="dialogFormVisible" width="600px" @close="closeDialog">
        <el-form :model="form" style="padding-left:7%" :rules="rules" ref="form">
          <el-form-item label="姓名" label-width="120px" prop="username">
            <el-input v-model="form.username" placeholder="请输入姓名" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="手机号" label-width="120px" prop="mobile">
            <el-input v-model="form.mobile" placeholder="请输入手机号" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="入职时间" label-width="120px" prop="timeOfEntry">
            <el-date-picker
              v-model="form.timeOfEntry"
              type="datetime"
              placeholder="请输入日期"
              style="width:300px"
              :editable="false"
              format="yyyy-MM-dd HH:mm:ss"
              default-time="12:00:00"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="聘用形式" label-width="120px" prop="formOfEmployment">
            <el-select v-model="form.inServiceStatus" placeholder="请选择" style="width:300px">
              <el-option :label="f.value" :value="f.id" v-for="f in formOf" :key="f.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工号" label-width="120px" prop="workNumber">
            <el-input v-model="form.workNumber" placeholder="请输入工号" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="部门" label-width="120px" prop="departmentId">
            <el-cascader
              @focus="getDepartments"
              :options="tree"
              :props="{ checkStrictly:true,value:'name',label:'name',expandTrigger:'hover' }"
              clearable
              placeholder="请选择部门"
              v-model="form.departmentName"
              style="width:300px"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="转正时间" label-width="120px">
            <el-date-picker
              v-model="form.correctionTime"
              type="datetime"
              placeholder="请输入日期"
              style="width:300px"
              :editable="false"
              format="yyyy-MM-dd HH:mm:ss"
              default-time="12:00:00"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button type="primary" @click="addEmployee">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </el-dialog>

      <roleAttr :roleAttrShow.sync="roleAttrShow" :userId="userId" ref="roleAttr" />
    </div>
  </div>
</template>

<script>
import moment from "moment";
import format from "@/api/constant/employees";
import roleAttr from "@/views/employee/components/roleAttr";
export default {
  data() {
    return {
      data: [],
      page: 1,
      size: 9,
      total: 0,
      tree: [],
      dialogFormVisible: false,
      form: {},
      rules: {
        username: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 6 个字之间",
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "手机号格式不正确",
            trigger: "blur"
          }
        ],
        timeOfEntry: [
          { required: true, message: "入职时间不能为空", trigger: "blur" }
        ],
        formOfEmployment: [
          { required: true, message: "聘用形式不能为空", trigger: "blur" }
        ],
        workNumber: [
          { required: true, message: "工号不能为空", trigger: "blur" }
        ],
        departmentId: [
          { required: true, message: "部门不能为空", trigger: "blur" }
        ]
      },
      roleAttrShow: false,
      userId: ""
    };
  },
  mounted() {
    this.getEmployeeList();
    this.getDepartments();
  },
  methods: {
    //获取员工列表
    async getEmployeeList() {
      try {
        let result = await this.$api.employee.getEmployeeList({
          page: this.page,
          size: this.size
        });
        this.total = result.total;
        this.data = result.rows;
      } catch (error) {
        this.$message.error(error);
      }
    },

    handleCurrentChange(val) {
      this.page = val;
      this.getEmployeeList();
    },

    //格式化聘请数据
    formatterInServiceStatus(val) {
      let result = format.hireType.find(item => item.id == val.inServiceStatus);
      return result?.value || "";
    },
    //格式化日期时间
    formatDate(val) {
      let result = moment(val.correctionTime).format("YYYY/DD/MM  hh:mm:ss");
      return result == "Invalid date" ? "未登记" : result;
    },

    //删除员工
    delEmployee(id) {
      this.$confirm("确认删除吗?", {
        cancelButtonText: "取消",
        confirmButtonText: "确认"
      })
        .then(async res => {
          try {
            await this.$api.employee.delEmployee(id);
            this.$message.success("删除成功");
            this.getEmployeeList();
          } catch (error) {
            this.$message.error(err);
          }
        })
        .catch(err => {
          this.$message.info(err);
        });
    },

    //获取部门列表
    async getDepartments() {
      let result = await this.$api.department.getDepartments();
      if (result) {
        this.tree = this.getDepartList(result.depts, "");
      }
    },

    //解构部门列表
    getDepartList(list, flag) {
      let arr = [];
      list.forEach(element => {
        if (element.pid == flag) {
          let children = this.getDepartList(list, element.id);
          if (children.length) {
            element.children = children;
          }
          arr.push(element);
        }
      });
      return arr;
    },

    //关闭对话款
    closeDialog() {
      this.dialogFormVisible = false;
      this.form = {};
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },

    //添加员工
    async addEmployee() {
      if (Array.isArray(this.form.departmentName)) {
        this.form.departmentName = this.form.departmentName?.join("/");
      }
      try {
        await this.$api.employee.addEmployee(this.form);
        this.dialogFormVisible = false;
        this.page = parseInt(this.total + 1 / this.size) + 1;
        this.$message.success("添加成功");
        this.getEmployeeList();
      } catch (error) {
        this.$message.info(error);
      }
    },

    //导入xlsx
    upload() {
      this.$router.push("/upload");
    },

    //导出xlsx
    async dataExport() {
      let info = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName"
      };
      let multiHeader = [["姓名", "主要信息", "", "", "", "部门"]];
      let result = await this.$api.employee.getEmployeeList({
        page: 1,
        size: this.total
      });
      let data = this.formatExcel(info, result.rows);
      console.log(data);
      import("@/vendor/Export2Excel").then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(info),
          data: data,
          multiHeader,
          merges: ["A1:A2", "B1:E1", "F1:F2"],
          filename: "员工信息表",
          bookType: "xlsx"
        });
      });
    },
    formatExcel(info, result) {
      return result.map(item => {
        return Object.keys(info).map(el => {
          if (el == "入职日期" || el == "转正日期") {
            let date = moment(item[info[el]]).format("YYYY/DD/MM");
            return date == "Invalid date" ? "未登记" : date;
          }
          return item[info[el]];
        });
      });
    },

    //查看
    showEmployee(id) {
      this.$router.push({
        name: "detail",
        params: {
          id
        }
      });
    },

    async role(row) {
      this.userId = row.id;
      try {
        await this.$refs.roleAttr.getRolesById(row.id);
      } catch (error) {}
      this.roleAttrShow = true;
    }
  },
  computed: {
    formOf() {
      return format.hireType;
    }
  },
  components: {
    roleAttr
  }
};
</script>

<style>
a {
  font-size: 12px;
  color: blue;
  margin-right: 20px;
}
.del {
  color: darkgrey !important;
}
.header {
  background-color: red;
}
</style>